import { EventImp } from './abstract'
import { Store } from "@/low-code/utils/store.js"
import { Message } from 'element-ui';

export class Event extends EventImp {
  __events;
  store
  constructor(store) {
    super()
    this.store = store
    store && this.__init()
  }

  __init() {
    this.store.eventMap && Object.entries(this.store.eventMap).map(([key, val]) => {
      try {
        this.on(key, eval(val))
      } catch (error) {
        console.log('自定义事件出现错误', error)
      }

    })
  }

  //添加监听
  on(key, listener) {
    //this.__events存储所有的处理函数
    if (!this.__events) {
      this.__events = {}
    }
    this.__events[key] = listener
    return this
  }
  //触发一个事件，也就是通知
  fire(key) {
    let _this = this
    if (!this.__events || !this.__events[key]) return
    var args = Array.prototype.slice.call(arguments, 1) || []

    if (!_this.store) {
      this.__events[key].apply(this, args)
      return false
    }

    return new Promise((resolve, reject) => {
      try {
        let parameter = [
          {
            form: _this.store.models,
            selector: _this.store.selector.bind(_this.store),
            axios: Store.axios,
            prefixUrl:Store.prefixUrl,
            messagePool: Store.messagePool,
            query:_this.store.query,
            params:_this.store.params,
            Message:Message,
            controller:_this.store.controller,
            setDialogParams: _this.store.dialogController.setDialogParams.bind( _this.store.dialogController),
            ...args[0]
          }
        ]
        let result = this.__events[key].apply(this, parameter)
        if (result && result.constructor == Promise) {
          result.then(res => {
            resolve(res)
          })
        } else {
          resolve(result)
        }

      } catch (error) {
        Message({
          showClose: true,
          message: '错了哦，自定义事件存在语法错误',
          type: 'error'
        })
        reject(error)
      }
    })
  }
  //取消监听
  off(key, listener) {
    if (!key && !listener) {
      this.__events = {}
    }
    if (key && !listener) {
      delete this.__events[key]
    }
    return this;
  }
}

export const event = new Event()

